<template>
  <section class="todoapp">
    <TodoHeader @addList="addList"></TodoHeader>
    <TodoMain
      :list="randerList"
      @delList="delList"
      @changeStatus="changeStatus"
      :isAll="isAll"
      @changeAll="changeAll"
    ></TodoMain>
    <TodoFooter
      :total="total"
      @clearList="clearList"
      :type="type"
      @changeType="changeType"
      v-show="list.length"
    >
    </TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('todoList')) || [
        { id: 1, name: '吃饭', isDone: false },
        { id: 2, name: '睡觉', isDone: true },
        { id: 3, name: '打豆豆', isDone: false }
      ],
      type: 'all'
    }
  },
  methods: {
    //1.删除功能
    delList (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    //2.修改状态
    changeStatus (id) {
      const res = this.list.find(item => item.id === id)
      res.isDone = !res.isDone
    },
    //3.添加功能
    addList (msg) {
      if (msg) {
        const obj = { id: +new Date(), name: msg, isDone: false }
        this.list = [obj, ...this.list]
      }
    },
    //5.清除功能
    clearList () {
      this.list = this.list.filter(item => !item.isDone)
    },
    //6.1.过滤
    changeType (type) {
      this.type = type
    },
    //7.2全选反选
    changeAll (flag) {
      this.list.forEach(item => (item.isDone = flag))
    }
  },
  computed: {
    //4.剩余功能
    total () {
      return this.list.filter(item => !item.isDone).length
    },
    //6.2.过滤
    randerList () {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item => !item.isDone)
        case 'completed':
          return this.list.filter(item => item.isDone)
        default:
          return this.list
      }
    },
    //7.1.全选反选
    isAll () {
      return this.list.every(item => item.isDone)
    }
  },
  watch: {
    //8.存储数据
    list: {
      deep: true,
      handler (value) {
        localStorage.setItem('todoList', JSON.stringify(value))
      },
      immediate: true
    }
  }
}
</script>

<style></style>
